import moment from 'moment';
// 数据转换，过滤

// 日期转格式
export const dateFormat = (date, withHms = false) => {
  if (withHms) {
    return date ? moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD/MM/YYYY') : '';
  } else {
    return date ? moment(date, 'YYYY-MM-DD').format('DD/MM/YYYY') : '';
  }
};

// 数字格式转换，处理千分位
export const thousandSeparator = (str, noPostfix = false) => {
  if (!str) return '-';
  str = String(str);
  let sign = false;
  if (str.indexOf('-') >= 0) {
    str = str.slice(1);
    sign = true;
  }
  let postfix = '';
  if (str.indexOf('.') >= 0) {
    postfix = str.substring(str.indexOf('.'));
    str = str.substring(0, str.indexOf('.'));
  } else {
    postfix = '.00';
  }
  let iNum = str.length % 3;
  let prev = '';
  let iNow = 0;
  let temp = '';
  let arr = [];
  if (iNum != 0) {
    prev = str.substring(0, iNum);
    arr.push(prev);
  }
  str = str.substring(iNum);
  for (let i = 0; i < str.length; i++) {
    iNow++;
    temp += str[i];
    if (iNow == 3 && temp) {
      arr.push(temp);
      temp = '';
      iNow = 0;
    }
  }
  return `${sign ? '-' : ''}${arr.join(',')}${noPostfix ? '' : postfix}`;
};

// 数字排序
export const numSortMethod = (a, b, prop) => {
  let numa = Number((a[prop] ?? '0').replace(/,/g, ''));
  let numb = Number((b[prop] ?? '0').replace(/,/g, ''));

  let _a = parseFloat(numa);
  let _b = parseFloat(numb);

  return _a - _b;
};

// 日期排序
export const dateSortMethod = (a, b, prop) => {
  let _a = Date.parse(new Date(a[prop]));
  let _b = Date.parse(new Date(b[prop]));
  return _a - _b;
};

//字符串排序
export const strSortMethod = (a, b, prop) => {
  let str1 = a[prop];
  let str2 = b[prop];
  // 处理数据为null或者空的情况
  if ((str1 == null || str1 == '') && (str2 == null || str2 == '')) {
    return 0;
  }
  if (str1 == null || str1 == '') {
    return -1;
  }
  if (str2 == null || str2 == '') {
    return 1;
  } // 比较字符串中的每个字符
  let c1;
  let c2; // 逐字比较返回结果
  for (let i = 0; i < str2.length; i++) {
    c1 = str1[i];
    if (i > str1.length - 1) {
      // 如果在该字符前，两个串都一样，str2更短，则str1较大
      return -1;
    }
    c2 = str2[i];

    if (c1 != c2) {
      return c1 > c2 ? 1 : -1;
    }
  }
  return 0;
};
